package com.estragon.jeuxdenfant;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.LoaderActionBarItem;
import greendroid.widget.PageIndicator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.estragon.jeuxdenfant.AnimationAdapter.AnimationIntrouvableException;
import com.estragon.sql.DatabaseHelper2;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import core.Animation;
import core.TypeAnimation;

public class MainActivity extends GDActivity implements OnPageChangeListener {
    /** Called when the activity is first created. */
	
	LoaderActionBarItem refresh;
	ActionBarItem add;
	ActionBarItem settings;
	AwesomePagerAdapter awesomeAdapter;
	PageIndicator indicator;
	private ViewPager awesomePager;
	public static final AsyncHttpClient client = new AsyncHttpClient();
	public static final String URL = "http://64cases.com/animation/API/api.php";
	public static final String NOMLOG = "JeuDenfant";
	HashMap<Integer, AnimationAdapter> adapters = new HashMap<Integer, AnimationAdapter>();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.main);
        getActionBar().removeViewAt(0);
        refresh = (LoaderActionBarItem) getActionBar().addItem(ActionBarItem.Type.Refresh).setDrawable(com.cyrilmottier.android.greendroid.R.drawable.gd_action_bar_refresh);
        //add = getActionBar().addItem(ActionBarItem.Type.Add).setDrawable(com.cyrilmottier.android.greendroid.R.drawable.gd_action_bar_add);
        settings = getActionBar().addItem(ActionBarItem.Type.Settings).setDrawable(com.cyrilmottier.android.greendroid.R.drawable.gd_action_bar_settings);
        
        awesomeAdapter = new AwesomePagerAdapter();
		awesomePager = (ViewPager) findViewById(R.id.pager);
		awesomePager.setAdapter(awesomeAdapter);
		awesomePager.setOnPageChangeListener(this);
        
        FrameLayout layout = (FrameLayout) findViewById(R.id.page_indicator_prev);
		indicator = new PageIndicator(this);
		indicator.setDotCount(awesomeAdapter.getCount());
		indicator.setGravity(Gravity.CENTER);
		layout.addView(indicator);
		verifPremiereFois();
    }
    
    public void verifPremiereFois() {
		int version = this.getPreferences(MODE_PRIVATE).getInt("derniereVersion", 0);
		if (version == 0) new AlertDialog.Builder(this).setMessage(
				"Merci d'avoir téléchargé cette application\n\nPour commencer, tapez sur l'icone pour charger les données")
				.setIcon(R.drawable.gd_action_bar_refresh)
				.setTitle("Hello !").setPositiveButton(android.R.string.ok, null).show();
		this.getPreferences(MODE_PRIVATE).edit().putInt("derniereVersion", SettingsActivity.getVersionCode()).commit();
	}

	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		// TODO Auto-generated method stub
		if (item == add) {
			
		}
		else if (item == refresh) {
			client.post(URL,new JsonHttpResponseHandler() {

				@Override
				public void onSuccess(JSONObject json) {
					// TODO Auto-generated method stub
					
					try {
						JSONArray types = json.getJSONArray("types");
						final List<TypeAnimation> listeTypes = new ArrayList<TypeAnimation>();
						for (int i = 0; i < types.length(); i++) {
							listeTypes.add(new TypeAnimation(types.getJSONObject(i)));
						}
						
						JSONArray animations = json.getJSONArray("animations");
						final List<Animation> listeAnimations = new ArrayList<Animation>();
						for (int i = 0; i < animations.length(); i++) {
							listeAnimations.add(new Animation(animations.getJSONObject(i)));
						}
						
						DatabaseHelper2.getHelper().getTypeAnimationDao().callBatchTasks(new Callable<Void>() {
							public Void call() throws Exception {
								
								DatabaseHelper2.getHelper().getTypeAnimationDao().delete(DatabaseHelper2.getHelper().getTypeAnimationDao().deleteBuilder().prepare());
								for (TypeAnimation typeAnimation : listeTypes) {
									DatabaseHelper2.getHelper().getTypeAnimationDao().create(typeAnimation);
								}
								return null;
							}
						});
						
						DatabaseHelper2.getHelper().getAnimationDao().callBatchTasks(new Callable<Void>() {
							public Void call() throws Exception {
								
								DatabaseHelper2.getHelper().getAnimationDao().delete(DatabaseHelper2.getHelper().getAnimationDao().deleteBuilder().prepare());
								for (Animation animation : listeAnimations) {
									DatabaseHelper2.getHelper().getAnimationDao().create(animation);
								}
								return null;
							}
						});
					}
					catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(MainActivity.this, "Réponse serveur invalide, avez vous la dernière version ?", 1).show();
					}
					
					refresh.setLoading(false);
					
					reload();
					
					super.onSuccess(json);
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					// TODO Auto-generated method stub
					refresh.setLoading(false);
					Toast.makeText(MainActivity.this, "Fail"+arg0, 1).show();
					super.onFailure(arg0, arg1);
				}
				
				
			});
		}
		else if (item == settings) {
			ouvrirSettings();
		}
		
		return super.onHandleActionBarItemClick(item, position);
	}
	
	public void reload() {
		startActivity(new Intent(this,MainActivity.class));
		finish();
	}
	
	public void ouvrirJeu(int idAnimation) {
		Intent intent = new Intent(this,JeuActivity.class);
		intent.putExtra("idAnimation",idAnimation);
		startActivity(intent);
	}
	
	public void ouvrirSettings() {
		Intent intent = new Intent(this,SettingsActivity.class);
		startActivity(intent);
	}
	
	private class AwesomePagerAdapter extends PagerAdapter{


		@Override
		public int getCount() {
			try {
				int nb = (int) DatabaseHelper2.getHelper().getTypeAnimationDao().countOf();
				indicator.setDotCount(nb);
				return nb;
			}
			catch (Exception e) {
				indicator.setDotCount(0);
				return 0;
			}
		}

		/**
		 * Create the page for the given position.  The adapter is responsible
		 * for adding the view to the container given here, although it only
		 * must ensure this is done by the time it returns from
		 * {@link #finishUpdate()}.
		 *
		 * @param container The containing View in which the page will be shown.
		 * @param position The page position to be instantiated.
		 * @return Returns an Object representing the new page.  This does not
		 * need to be a View, but can be some other container of the page.
		 */
		@Override
		public Object instantiateItem(View collection, final int position) {
			LayoutInflater inflater = (LayoutInflater) collection.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View view = inflater.inflate(R.layout.page, null);
			ListView liste = (ListView) view.findViewById(R.id.awesomelist);
			
			AnimationAdapter oldAdapter = adapters.get(position);
			if (oldAdapter == null) {
				AnimationAdapter adapter = new AnimationAdapter(view.getContext(),position+1);
				adapters.put(position,adapter);
				liste.setAdapter(adapter);
			}
			else {
				liste.setAdapter(oldAdapter);
			}
			final AnimationAdapter adapter = adapters.get(position);
			
			liste.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int positionDansLaListe, long id) {
					try {
						int idAnimation = adapter.getIdAnimationFromPosition(positionDansLaListe);
						ouvrirJeu(idAnimation);
					}
					catch (AnimationIntrouvableException e) {
						
					}
				}
			});

			liste.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int position, long id) {

					return true;
				}
			});



			((ViewPager) collection).addView(view,0);
		

			return view;
		}


		/**
		 * Remove a page for the given position.  The adapter is responsible
		 * for removing the view from its container, although it only must ensure
		 * this is done by the time it returns from {@link #finishUpdate()}.
		 *
		 * @param container The containing View from which the page will be removed.
		 * @param position The page position to be removed.
		 * @param object The same object that was returned by
		 * {@link #instantiateItem(View, int)}.
		 */
		@Override
		public void destroyItem(View collection, int position, Object view) {
			((ViewPager) collection).removeView((View) view);
		}



		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view==object;
		}


		/**
		 * Called when the a change in the shown pages has been completed.  At this
		 * point you must ensure that all of the pages have actually been added or
		 * removed from the container as appropriate.
		 * @param container The containing View which is displaying this adapter's
		 * page views.
		 */
		@Override
		public void finishUpdate(View arg0) {}



		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {}

	}
	
	

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int arg0) {
		// TODO Auto-generated method stub
		majCurrentTab();
	}
	
	void majIndicator() {
		indicator.setActiveDot(awesomePager.getCurrentItem());
	}

	void majCurrentTab() {
		try {
			majIndicator();
			//adapters.get(awesomePager.getCurrentItem()).notifyDataSetChanged();
		}
		catch (Exception e) {
			
		}
	}
    
    
}